package com.qili.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.entity.base.BaseDict;
import com.qili.entity.base.FormType;
import com.qili.entity.supervisor.SupervisorFile;
import com.qili.entity.supervisor.SupervisorProjectForms;
import com.qili.entity.supervisor.dto.SupervisorProjectFromsDTO;
import com.qili.service.it.FormBaseService;
import com.qili.service.it.ItDicService;
import com.qili.service.supervisor.SupervisorProjectFormsDataService;
import com.qili.service.supervisor.SupervisorProjectFormsService;
import com.qili.util.BeanUtil;
import com.qili.util.CommonUtil;
import com.qili.util.DateUtil;
import com.qili.util.JsonUtil;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liuyang
 * @date 2021/3/29
 * @description
 */
@Log
@Controller
@RequestMapping("/it/form")
public class FormController {

    @Autowired
    ItDicService dicService;
    @Autowired
    SupervisorProjectFormsService spfService;
    @Autowired
    SupervisorProjectFormsDataService spfdService;
    @Autowired
    @Qualifier("FormBaseService")
    FormBaseService formBaseService;

    /**
     * 显示表单页面
     * @param formCode      表单类型编码
     * @param model
     * @param temp          上传的文件是否保存到临时文件   temp为1则保存到临时文件    否则则保存到真实文件路径
     * @param dicId         当前文件夹 supervisor_file表id
     * @param edit          如果该字段为"1",那么表示当前为编辑页面
     * @return
     */
    @RequestMapping("/show")
    @RequiresPermissions("it:redact")
    public String showFormPage(String formCode, Model model,String temp,String dicId,String edit){
        //如果是新增表单页面,那么一定要有formCode参数
        if((StringUtils.isBlank(edit) && StringUtils.isBlank(formCode)) || StringUtils.isBlank(dicId)) {
            throw new RuntimeException("参数异常");
        }
        model.addAttribute("dicId",dicId);
        boolean editPage = StringUtils.isNotBlank(edit) && "1".equals(edit);

        SupervisorFile thisFile = dicService.selectByPrimaryKey(dicId);

        if(editPage){
            model.addAttribute("edit","1");
            //如果是编辑,formCode会为空,那么需要根据dicId查询出formCode:
            //查询表单核心目录文件:
            String formCenterFileId = formBaseService.getFormCenterFileId(dicId);
            if(StringUtils.isBlank(formCenterFileId)){
                if(StringUtils.isNotBlank(thisFile.getLinkId())){
                    SupervisorProjectForms supervisorProjectForms = spfService.selectByPrimaryKey(thisFile.getLinkId());
                    if(null != supervisorProjectForms){
                        //正中参编标准走这里
                        formCode = "110001";
                        SupervisorProjectFromsDTO dto = new SupervisorProjectFromsDTO();
                        BeanUtil.copyNotNullBean(supervisorProjectForms,dto);
                        model.addAttribute("formData",dto);
                        //获取表单数据:
                        formBaseService.getFormData(formCode,dto,model);
                        model.addAttribute("parentDicId",thisFile.getSuperiorId());
                    }
                }else{
                    throw new RuntimeException("获取表单数据时,没有获取到核心文件夹id");
                }
            }else{
                model.addAttribute("formCenterFileId",formCenterFileId);
                SupervisorFile formCenterFile = dicService.selectByPrimaryKey(formCenterFileId);
                formCode = formCenterFile.getType();
                //查询对应的form数据:
                SupervisorProjectForms forms = spfService.selectByPrimaryKey(formCenterFile.getLinkId());

                if(null != forms){
                    SupervisorProjectFromsDTO dto = new SupervisorProjectFromsDTO();
                    BeanUtil.copyNotNullBean(forms,dto);
                    model.addAttribute("formData",dto);
                    //获取表单数据:
                    formBaseService.getFormData(formCode,dto,model);
                }
            }
        }
        String returnPage = "";
        formCode = formCode.trim().toLowerCase();
        if(formCode.equals(FormType.ZZCBBZ.getCode())){
            //正中参编标准页面
            /*标准级别*/
            List<BaseDict> bzjbList = DictUtil.getDictByType(DictTypes.BZJB);
            model.addAttribute("bzjbList",bzjbList);
            /*标准状态*/
            List<BaseDict> stateList = DictUtil.getDictByType(DictTypes.STATE);
            model.addAttribute("stateList",stateList);
            /*正中角色*/
            List<BaseDict> zzjsList = DictUtil.getDictByType(DictTypes.ZZJS);
            model.addAttribute("zzjsList",zzjsList);
            /*标准委员会*/
            List<BaseDict>bzwyhList = DictUtil.getDictByType(DictTypes.BZWYH);
            model.addAttribute("bzwyhList",bzwyhList);
            returnPage = "form/zzcbbz";
        }else if(formCode.equals(FormType.ZL.getCode())){
            //专利页面
            /*专利类型*/
            List<BaseDict> zllxList = DictUtil.getDictByType(DictTypes.ZLLX);
            model.addAttribute("zllxList",zllxList);
            /*阶段*/
            List<BaseDict> itjdList = DictUtil.getDictByType(DictTypes.ITJD);
            model.addAttribute("itjdList",itjdList);
            returnPage = "form/zhuanli";
        }else if(formCode.equals(FormType.RZ.getCode())){
            //软著页面
            returnPage = "form/ruanzhu";
        }else if(formCode.equals(FormType.JCDLBT.getCode())){
            //集成电路布图页面
            returnPage = "form/jcdlbt";
        }else if(formCode.equals(FormType.LW.getCode())){
            //论文页面
            /*期刊类型*/
            List<BaseDict> qklxList = DictUtil.getDictByType(DictTypes.QKLX);
            model.addAttribute("qklxList",qklxList);
            /*所属期刊分类*/
            List<BaseDict> qkflList = DictUtil.getDictByType(DictTypes.QKFL);
            model.addAttribute("qkflList",qkflList);
            returnPage = "form/lunwen";
        }else if(formCode.equals(FormType.SZ.getCode())){
            //书著页面
            returnPage = "form/shuzhu";
        }else if(formCode.equals(FormType.KYXMK.getCode())){
            //科研项目库
            //项目级别
            List<BaseDict> xmjbList = DictUtil.getDictByType(DictTypes.XMJB);
            model.addAttribute("xmjbList",xmjbList);
            //计划类别
            List<BaseDict> jhlbList = DictUtil.getDictByType(DictTypes.JHLB);
            model.addAttribute("jhlbList",jhlbList);
            //项目进度
            List<BaseDict> xmjdList = DictUtil.getDictByType(DictTypes.XMJD);
            model.addAttribute("xmjdList",xmjdList);
            returnPage = "form/keyanxiangmu";
        }
        model.addAttribute("formCode",formCode);
        if(StringUtils.isNotBlank(temp) && "1".equals(temp)){
            model.addAttribute("temp",temp);
        }
        return returnPage;
    }


    /**
     * 判断该文件或者文件夹是否是表单文件或表单文件的子文件
     * @param fileId
     * @return  是,返回true 否则返回false
     */
    public boolean ifFileForm(String fileId){
        //判断该文件夹是不是form文件夹或者是form文件夹的子文件夹:
        List<BaseDict> formFileDictList = DictUtil.getDictByType(DictTypes.FORMFILE);
        List<String> formFileIds = formFileDictList.stream().map(BaseDict::getBadtCode).collect(Collectors.toList());
        SupervisorFile supervisorFile = dicService.selectByPrimaryKey(fileId);
        //获取所有是表单文件的id:
        if(CollectionUtil.isNotEmpty(formFileIds) && supervisorFile != null){
            //如果当前文件正好是表单目录:
            if(formFileIds.contains(supervisorFile.getId())){
                return true;
            }else{
                if(StringUtils.isNotBlank(supervisorFile.getSuperiorId())){
                    return ifFileForm(supervisorFile.getSuperiorId());
                }
                return false;
            }
        }else{
            return false;
        }
    }

    public boolean ifFileFroject(String fileId){
        //判断该文件夹是不是form文件夹或者是form文件夹的子文件夹:
        List<BaseDict> projectFileDictList = DictUtil.getDictByType(DictTypes.XMWJ);
        List<String> projectFileIds = projectFileDictList.stream().map(BaseDict::getBadtCode).collect(Collectors.toList());
        SupervisorFile supervisorFile = dicService.selectByPrimaryKey(fileId);
        //获取所有是表单文件的id:
        if(CollectionUtil.isNotEmpty(projectFileIds) && supervisorFile != null){
            //如果当前文件正好是表单目录:
            if(projectFileIds.contains(supervisorFile.getId())){
                return true;
            }else{
                if(StringUtils.isNotBlank(supervisorFile.getSuperiorId())){
                    return ifFileFroject(supervisorFile.getSuperiorId());
                }
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 表单提交入口
     * @param forms
     * @return
     */
    @RequestMapping("insertBook")
    @ResponseBody
    public JsonUtil insertBook(SupervisorProjectFromsDTO forms){
        boolean ifNew = StringUtils.isBlank(forms.getSpfId());
        JsonUtil jso=new JsonUtil();
        String userId = CommonUtil.getUserId();
        if(ifNew){
            //新增
            forms.setCreateDate(DateUtil.getCurrentDateTimeString());
            forms.setCreateUserId(userId);
            forms.setSpfId(IdUtil.simpleUUID());
            if(spfService.insertSelective(forms)<0){
                jso.setFlag(false);
                jso.setMsg("新增失败");
                return jso;
            }
        }else{
            //更新：
            spfService.updateByPrimaryKeySelective(forms);
        }
        formBaseService.saveFormFile(forms,ifNew);
        formBaseService.saveFormData(forms,ifNew);
        jso.setFlag(true);
        if(ifNew){
            jso.setMsg("新增成功");
        }else{
            jso.setMsg("更新成功");
        }
        return jso;
    }


    /**
     * 根据表单文件类型和所在文件,查询对应的文件
     * @param dicId
     * @param formFileType
     * @return
     */
    @ResponseBody
    @RequestMapping("/getFileList")
    public JsonUtil getFormFileList(String dicId,String formFileType,String spfId){
        JsonUtil result = new JsonUtil();
        try{
            if(StringUtils.isBlank(dicId) || StringUtils.isBlank(formFileType)){
                throw new RuntimeException("参数错误");
            }
            Example example = new Example(SupervisorFile.class);
            List<SupervisorFile> supervisorFiles = new ArrayList<SupervisorFile>();
            if(formFileType.startsWith("110001")){
                //正中参编标准文件:
                example.and().andEqualTo("type",formFileType)
                        .andEqualTo("zskfileType","2")
                        .andEqualTo("deleteState","1")
                        .andEqualTo("linkId",spfId);
                example.setOrderByClause("create_date desc");
            }else{
                //根据文件夹/文件id查询对应的表单核心文件id:
                String formCenterFileId = formBaseService.getFormCenterFileId(dicId);
                example.and().andEqualTo("type",formFileType)
                        .andEqualTo("zskfileType","2")
                        .andEqualTo("deleteState","1")
                        .andEqualTo("linkId",formCenterFileId);
                example.setOrderByClause("create_date desc");
            }
            supervisorFiles = dicService.selectByExample(example);
            result.setData(supervisorFiles);
            result.setFlag(true);
            result.setMsg("获取成功");
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return JsonUtil.error(e.getMessage());
        }
    }

}
